

package com.controller;

import com.entity.CourseEntity;
import com.entity.LearningProgressEntity;
import com.entity.LessonEntity;
import com.entity.OverallProgressEntity;
import com.service.CourseService;
import com.service.LearningProgressService;
import com.service.LessonService;
import com.service.OverallProgressService;
import com.utils.R; // <-- 【关键】补上这一行对 R 类的导入

// 导入Spring的注解
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

// 导入Java Servlet的类
import javax.servlet.http.HttpServletRequest;

// 导入Java工具类
import java.util.List;
/**
 * 学习进度控制类
 */
@RestController
@RequestMapping("/learningprogress")
public class LearningProgressController {

    @Autowired
    private LearningProgressService learningProgressService;

    @Autowired
    private OverallProgressService overallProgressService;

    @Autowired
    private LessonService lessonService;

    @Autowired
    private CourseService courseService;
    /**
     * 获取当前登录用户的所有学习进度
     * @param request
     * @return
     */
    @GetMapping("/myProgress")
    public R getMyProgress(HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error(401, "用户未登录");
        }
        // 调用新的 Service 方法
        List<LearningProgressEntity> progressList = learningProgressService.getProgressWithLessonInfoByUserId(userId);
        return R.ok().put("data", progressList);
    }

    /**
     * 获取当前用户对某一课程的学习进度
     */
    @GetMapping("/byCourseId")
    public R getProgressByCourseId(@RequestParam("courseId") Long courseId, HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error(401, "用户未登录");
        }
        if (courseId == null) {
            return R.error("courseId 不能为空");
        }
        // 调用新的 Service 方法，传入 courseId 和 userId
        List<LearningProgressEntity> progressList = learningProgressService.getProgressWithLessonInfoByCourseIdAndUserId(courseId, userId);
        return R.ok().put("data", progressList);
    }

    /**
     * 获取当前用户的ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        Object userIdObj = request.getSession().getAttribute("userId");
        if (userIdObj != null) {
            return Long.valueOf(userIdObj.toString());
        }
        return null;
    }


    /**
     * 保存或更新学习进度
     * 前端 POST 请求，传入 LearningProgressEntity 对象（包含 lessonId, progressSeconds, isCompleted 等）
     */
    @RequestMapping("/saveOrUpdate")
    public R saveOrUpdate(@RequestBody LearningProgressEntity learningProgress, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        if (userId == null) {
            return R.error("用户未登录或无法获取用户ID");
        }
        learningProgress.setUserId(userId); // 设置当前用户ID

        // 1. 查询是否存在该用户对该课时的学习进度
        LearningProgressEntity existingProgress = learningProgressService.getProgressByUserIdAndLessonId(userId, learningProgress.getLessonId());

        Long courseId = null;
        if (learningProgress.getLessonId() != null) {
            // 根据 lessonId 获取其所属的 courseId
            LessonEntity lesson = lessonService.selectById(learningProgress.getLessonId());
            if (lesson != null) {
                courseId = lesson.getCourseId();
            }
        }

        if (existingProgress != null) {
            // 2. 如果存在，则更新
            if(existingProgress.getProgressSeconds()<=learningProgress.getProgressSeconds()){ //
                existingProgress.setProgressSeconds(learningProgress.getProgressSeconds());
            }
            existingProgress.setCompleted(learningProgress.getCompleted());
            if(existingProgress.getProgressPercent()<=learningProgress.getProgressPercent()){
                existingProgress.setProgressPercent(learningProgress.getProgressPercent());
            }
            existingProgress.setLastPosition(learningProgress.getLastPosition());

            learningProgressService.updateById(existingProgress);
        } else {
            // 3. 如果不存在，则插入新进度
            learningProgressService.insert(learningProgress);
        }

        // 4. 同步更新/保存用户的整体课程学习进度
        if (userId != null && courseId != null) {
            overallProgressService.calculateAndSaveOverallProgress(userId, courseId);
        } else {
            // 应该记录日志或抛出异常，说明无法获取 courseId
            System.err.println("无法获取 lessonId=" + learningProgress.getLessonId() + " 对应的 courseId，跳过整体进度计算。");
        }


        return R.ok("学习进度保存成功");
    }

    /**
     * 获取特定课程的学习进度
     * 前端 GET 请求，传入 lessonId
     */
    @RequestMapping("/info")
    public R getProgressInfo(@RequestParam Long lessonId, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        if (userId == null) {
            return R.error("用户未登录或无法获取用户ID");
        }

        LearningProgressEntity progress = learningProgressService.getProgressByUserIdAndLessonId(userId, lessonId);
        if (progress != null) {
            return R.ok().put("data", progress);
        } else {
            return R.ok().put("data", null).put("msg", "该课程无学习进度记录"); // 返回空数据表示无记录
        }
    }


    /**
     * 获取用户对某一门课的总体学习进度
     */
    @GetMapping("/getByCourseId")
    public R getOverallProgressByCourseId(@RequestParam("courseId") Long courseId, HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        if (userId == null) {
            return R.error(401, "用户未登录或无法获取用户ID");
        }
        if (courseId == null) {
            return R.error("课程ID不能为空");
        }
        CourseEntity course=courseService.selectById(courseId);
        OverallProgressEntity overallProgress = overallProgressService.getOverallProgressByUserIdAndCourseId(userId, courseId);

        if (overallProgress == null) {
            // 如果没有找到记录，可以返回一个特定的状态或空数据
            return R.ok("暂无该课程的整体学习进度记录").put("data", null);
        } else {
            overallProgress.setTitle(course.getTitle());
            overallProgress.setCourseCoverImageUrl(course.getCoverImageUrl());
            return R.ok().put("data", overallProgress);
        }
    }


    /**
     * 获取当前用户对所有课程的学习进度
     */
    @GetMapping("/myOverallProgresses")
    public R getMyOverallProgresses(HttpServletRequest request) {
        Long userId = getCurrentUserId(request);
        if (userId == null) {
            return R.error(401, "用户未登录或无法获取用户ID");
        }

        List<OverallProgressEntity> overallProgressList = overallProgressService.getUserAllOverallProgresses(userId);

        if (overallProgressList == null || overallProgressList.isEmpty()) {
            return R.ok("暂无整体学习进度记录").put("data", new java.util.ArrayList<>()); // 返回空列表
        } else {
            return R.ok().put("data", overallProgressList);
        }
    }
}
